import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from aws_model.athena_submit import submit
from config import hour_bucket
from sql_lambda.delete import delete
from base_class.inspect_logging import print_to_log
import datetime
import json
from aws_model.aws_stepfunc import send_task_success, send_task_failure


def ac_online_rate_hour(event):
    date = event.get('p_date')
    if not date:
        beijing = datetime.timezone(datetime.timedelta(hours=7))
        date = datetime.datetime.now(tz=beijing).strftime('%Y-%m-%d-%H')
    delete(hour_bucket,f'ads/ac_online_rate_hour/p_date={date}')
    filter_date = date[0:10]
    filter_hour = date[11:13]
    table_name = sys._getframe().f_code.co_name
    sql = f'''insert into ads.ac_online_rate_hour
			(	
				select * from 
                (
                    select
                        t.model,t.inner_version,t.outer_version,t.region,t.province,t.city,
                        t.online_count,
                        t.open_count,
                        t2.activation_count,
                        t2.install_count,
                        '{filter_date}' as record_date,
                        '{filter_hour}' as record_hour,
                        '{date}' as p_date
                    from
                        (
                        select
                            model,
                            if(inner_version is null,'',inner_version) as inner_version,
                            if(outer_version is null,'',outer_version) as outer_version,
                            if(region is null,'',region) as region,
                            if(province is null,'',province) as province,
                            if(city is null,'',city) as city,
                            count(1) as online_count,
                            count_if(open=1) as open_count
                        from
                            ads.ac_online_device
                        where
                            p_date = '{date}'
                        group by
                            model,inner_version,outer_version,region,province,city
                        )t
                    left join
                        (select
                            model,
                            if(inner_version is null,'',inner_version) as inner_version,
                            if(outer_version is null,'',outer_version) as outer_version,
                            if(region is null,'',region) as region,
                            if(province is null,'',province) as province,
                            if(city is null,'',city) as city,
                            count_if(first_report_time is not null) as activation_count,
                            count_if(source != 'KYD') as install_count
                        from
                            dws.ac_all_device_life_td
                        group by
                            model,inner_version,outer_version,region,province,city
                        ) t2
                    on t.model = t2.model and t.inner_version = t2.inner_version and t.outer_version = t2.outer_version and t.region = t2.region and t.province = t2.province
                        and t.city = t2.city
				)
				where city is not null and city != ''
			)'''
    athena_response = submit(sql)
    print_to_log("athena_response: ", athena_response)
    output = {"msg": f"{table_name} submit ok", "Payload": {}}
    output = json.dumps(output)
    step_response = send_task_success(tasktoken, output)
    print_to_log("step_response: ", step_response)


if __name__ == '__main__':
    try:
        event = json.loads(sys.argv[1])
        tasktoken = event.get('TaskToken')
        ac_online_rate_hour(event)
    except Exception as e:
        print_to_log("athena_submit 失败")
        print_to_log("原因： ", str(e))
        send_task_failure(str(e), f'执行{sys._getframe().f_code.co_filename}错误', tasktoken)
